import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import { PageLoading } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from 'umi';
import { history } from 'umi';
import RightContent from '@/components/RightContent';
import Footer from '@/components/Footer';
import { queryCurrentUser } from './services/user/api';
import { amapKey } from './utils/amap';

const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';

// document.ejs迁移
const aMapScript = document.createElement('script');
aMapScript.type = 'text/javascript';
aMapScript.src = `https://webapi.amap.com/maps?v=1.4.15&key=${amapKey}`;
document.getElementById('root')?.appendChild(aMapScript);

aMapScript.onload = () => {
  // 当前脚本需要在Amap后加载
  const aMapUIScript = document.createElement('script');
  aMapUIScript.src = '//webapi.amap.com/ui/1.1/main.js';
  document.getElementById('root')?.appendChild(aMapUIScript);
};

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> {
  const fetchUserInfo = async () => {
    try {
      const currentUser = await queryCurrentUser();
      return currentUser;
    } catch (error) {
      history.replace('/');
    }
    return undefined;
  };
  const currentUser = await fetchUserInfo();

  return {
    currentUser,
    settings: {},
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  return {
    rightContentRender: () => <RightContent />,
    // disableContentMargin: false,
    disableContentMargin: true,
    // waterMarkProps: { /* 水印 */
    //   content: initialState?.currentUser?.userName,
    // },
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        queryCurrentUser()
          .then(() => {
            history.push(location?.pathname || '/dashboard');
          })
          .catch(() => {
            history.push(loginPath);
          });
      }
    },
    links: isDev ? [] : [],
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    ...initialState?.settings,
  };
};
